import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';

export default function useProjectId(immediate = true) {
  // 获取项目id, 同时监听回调
  const projectId = ref('');
  let func = () => {
    // noop
  };
  const setCallback = (cb: () => void) => {
    // TODO: 回调函数参数的处理
    func = cb;
  };
  const route = useRoute();
  watch(
    () => route.params,
    (newV) => {
      // 当projectId发生变化时才执行回调
      const newId = (newV.projectId as string) || '';
      if (projectId.value !== newId) {
        projectId.value = newId;
        // 初次进入时回调函数会未赋值
        func();
      }
    },
    { immediate }
  );
  return { projectId, setCallback };
}
